from django.core.cache import cache
from django.db import models, transaction

from utils.models import BaseModel


# Create your models here.


class NavCategory(BaseModel):
    """
    导航分类表
    """
    name = models.CharField(max_length=100, verbose_name="导航分类名称")
    weight = models.IntegerField(default=0, verbose_name="权重")
    external_link = models.CharField(max_length=200, null=True, blank=True, verbose_name="外链地址")

    class Meta:
        db_table = "tb_nav_category"
        verbose_name = "导航分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class CourseCategory(BaseModel):
    """
    课程分类表
    """
    name = models.CharField(max_length=100, verbose_name="课程分类名称")
    level = models.IntegerField(verbose_name="课程分类级别")
    desp = models.TextField(verbose_name="课程分类描述")
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name="父级分类id")

    class Meta:
        db_table = "tb_course_category"
        verbose_name = "课程分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Banner(BaseModel):
    """
    轮播图
    """
    title = models.CharField(max_length=100, verbose_name="轮播图标题")
    image = models.CharField(max_length=200, verbose_name="轮播图图片")
    link = models.URLField(max_length=200, verbose_name="轮播图链接")
    note = models.CharField(max_length=200, null=True, blank=True, verbose_name="轮播图备注")

    class Meta:
        db_table = "tb_banner"
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        """
        保存对象并清除相关缓存

        参数:
            *args: 位置参数，传递给父类的save方法
            **kwargs: 关键字参数，传递给父类的save方法

        返回值:
            无返回值
        """
        # 调用父类的save方法执行实际保存操作
        super().save(*args, **kwargs)
        cache_key = "code_env_spaces:home:banner:list"

        # 事务提交后再清理缓存，并使用 Celery 做延时双删兜底
        def _after_commit():
            cache.delete(cache_key)
            try:
                from home.tasks import schedule_delayed_delete

                schedule_delayed_delete([cache_key], base_delay_seconds=5, jitter_seconds=3)
            except Exception:
                # 兜底：即使 Celery 不可用，也至少完成一次删除
                pass

        transaction.on_commit(_after_commit)

    def delete(self, *args, **kwargs):
        """
        删除对象并清除相关缓存

        参数:
            *args: 位置参数，传递给父类的delete方法
            **kwargs: 关键字参数，传递给父类的delete方法

        返回值:
            无返回值
        """
        # 调用父类的delete方法执行实际删除操作
        super().delete(*args, **kwargs)
        cache_key = "code_env_spaces:home:banner:list"

        def _after_commit():
            cache.delete(cache_key)
            try:
                from home.tasks import schedule_delayed_delete

                schedule_delayed_delete([cache_key], base_delay_seconds=5, jitter_seconds=3)
            except Exception:
                pass

        transaction.on_commit(_after_commit)
